package net.wang.zk.demo;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING) //按照方法的名称执行单元测试
public class ZKNodeOperator {

    private static final String zkServerPath = "localhost:2181";  //单个节点连接

    public static final Integer timeout = 5000;
    ZooKeeper zooKeeper = null;
    CountDownLatch countDownLatchConnect = new CountDownLatch(1);


    @Before
    public void connect() throws IOException {
        zooKeeper = new ZooKeeper(zkServerPath, timeout, watchedEvent -> {
            log.info("===> watch = {}", watchedEvent.getType());
            try {
                countDownLatchConnect.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }

    @Test
    public void test1_CreateNode() {
        log.info("===>客户端连接状态：{}", zooKeeper.getState());
        zooKeeper.create("/testNode", "testnode".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {
            log.info("===>rc = {},path = {},ctx = {},name = {}", rc, path, ctx, name);
        }, "{create:ok}");


    }

    @Test
    public void test2_GetNodeData() throws Exception {
        byte[] data = zooKeeper.getData("/testNode", true, new Stat());
        log.info("===> get data : {}", new String(data));

    }

    @Test
    public void test3_UpdateNodeData() throws Exception {
        Stat stat = zooKeeper.setData("/testNode", "SETDATA".getBytes(), 0);
        log.info("===> update stat : {}", stat);
    }

    @Test
    public void test4_RemoveNodeData() {
        zooKeeper.delete("/testNode", 1, (rc, path, ctx) -> log.info("====> rc = {},path = {},ctx = {}", rc, path, ctx), "delete ok");

    }

    @After
    public void closeConnect() throws InterruptedException {
        zooKeeper.close();
        countDownLatchConnect.countDown();
    }
}
